package com.jblog.common.web.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import com.jblog.common.util.HtmlUtils;
import com.jblog.common.util.StrUtils;
import com.jblog.common.web.freemarker.exception.MustNotNullException;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
/**
 * truncate the content and append a symbol after
 * <br>
 * for example:(include HTML)<br>
 * <code>
 * Before: abcdefg<br>
 * &nbsp;Afger: abcd...
 * </code>
 * <br>and so on
 */
public class HtmlCutDirective implements TemplateDirectiveModel {

    public static final String PARAM_S = "s";
    public static final String PARAM_LEN = "len";
    public static final String PARAM_APPEND = "append";
    public static final String PARAM_TYPE = "type";
    
    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
            TemplateDirectiveBody body) throws TemplateException, IOException {
        String s = DirectiveUtils.getString(PARAM_S, params);
        Integer len = DirectiveUtils.getInt(PARAM_LEN, params);
        String append = DirectiveUtils.getString(PARAM_APPEND, params);
        String type = DirectiveUtils.getString(PARAM_TYPE, params).toUpperCase();
        
        if (null == s) {
            throw new MustNotNullException(PARAM_S);
        } else {
            Writer out = env.getOut();
            if (null == len) {
                out.append(s);
            } else {
                if (Type.TEXT == Type.valueOf(type)) {
                    out.append(StrUtils.textCut(s, len, append));
                } else if(Type.HTML == Type.valueOf(type)) {
                    out.append(HtmlUtils.htmlCut(s, len, append));
                } else {
                    throw new RuntimeException("parameter type must be \"TEXT\" or \"HTML\"");
                }
            }
        }
    }
    
    public enum Type {
        TEXT,
        HTML
    }

}
